import dayjs from '@/utils/dayjs.min.js';

Component({

  //本项目定义的日期对象类型
  // DateObject:{
  //   value: '', //YYYY-MM-DD,
  //   year:0,
  //   month:0,
  //   date:0
  // }

  /**
   * 组件的属性列表
   */
  properties: {
    options: {
      type: Object,
      value: {}
    },
    timeMap: {
      type: Object,
      value: {},
      observer(newVal, oldVal) {
        this.getCalendarPage();
      }
    }
  },


  /**
   * 组件的初始数据
  */

  data: {
    config: {
      weeks: ['日', '一', '二', '三', '四', '五', '六']
    },
    calendar: [],
    today: {
      year: dayjs().year(),
      month: dayjs().month(),
      date: dayjs().date(),
      value: dayjs().format('YYYY-MM-DD'),
    },
    current: dayjs().format('YYYY-MM-DD'),
    showMonth: dayjs().month(),
    showMonthText: dayjs().format('YYYY/MM')
  },

  attached() {
    this.currentMonthObj = dayjs();
    // this.getCalendarPage();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onSelectDate(e) {
      const day = e.currentTarget.dataset.day;
      this.setData({ current: day.value });
      this.triggerEvent("changeDate", day.value);
      console.log("select date：", day)
    },

    toLastMonth() {
      const lastMonthObj = this.currentMonthObj.month(this.currentMonthObj.month() - 1);
      this.changeMonth(lastMonthObj);
      // console.log("last month", lastMonthObj.month());
    },

    toNextMonth() {
      const nextMonthObj = this.currentMonthObj.month(this.currentMonthObj.month() + 1);
      this.changeMonth(nextMonthObj);
      // console.log("next month", nextMonthObj.month());
    },

    changeMonth(monthObj) {
      this.currentMonthObj = monthObj;
      this.getCalendarPage(new Date(monthObj));
      this.setData({
        showMonth: monthObj.month(),
        showMonthText: monthObj.format('YYYY/MM'),
      })
    },

    getCalendarPage(date = new Date()) {
      const year = date.getFullYear();
      const month = date.getMonth();

      // 获取当前月份的第一天和最后一天
      const firstDayOfMonth = new Date(year, month, 1);
      const lastDayOfMonth = new Date(year, month + 1, 0);
      const totalDaysInMonth = lastDayOfMonth.getDate();

      // 获取上个月的最后一天
      const lastDayOfPrevMonth = new Date(year, month, 0);
      const totalDaysInPrevMonth = lastDayOfPrevMonth.getDate();

      // 获取当前月份的第一天是星期几
      const firstDayOfWeek = firstDayOfMonth.getDay(); // 0是星期天，1是星期一，依此类推

      // 计算当前月份的日历页
      const calendar = [];
      let week = new Array(7).fill(null); // 一周7天，初始化为空

      let currentDay = 1;
      let prevMonthDay = totalDaysInPrevMonth - firstDayOfWeek + 1; // 上月补充的第一天日期
      let nextMonthDay = 1;

      // 填充日历
      for (let i = 0; i < 6; i++) { // 最多6周
        for (let j = 0; j < 7; j++) {
          if (i === 0 && j < firstDayOfWeek) {
            // 填充前一个月的日期
            week[j] = this.formatCalendarItem({
              date: prevMonthDay++,
              month: month === 0 ? 11 : month - 1, // 前一个月
              year: month === 0 ? year - 1 : year
            })
          } else if (currentDay <= totalDaysInMonth) {
            // 填充当前月的日期
            week[j] = this.formatCalendarItem({
              date: currentDay++,
              month: month,
              year: year
            })
          } else {
            // 填充下一个月的日期
            week[j] = this.formatCalendarItem({
              date: nextMonthDay++,
              month: month === 11 ? 0 : month + 1,
              year: month === 11 ? year + 1 : year,
            })
          }
        }

        // 将每周的日期加入到日历
        if (week.some(day => day && day.month === month)) {
          calendar.push(week);
        }
        week = new Array(7).fill(null); // 重置为下一周
      }

      // console.log(calendar);
      this.setData({ calendar })
    },

    formatCalendarItem(data) {
      const { year, month, date } = data;
      const value = `${year}-${month >= 9 ? (month + 1) : '0' + (month + 1)}-${date >= 10 ? date : '0' + date}`;

      //特殊处理的参数↓
      const timeList = this.properties.timeMap[value] || [];
      const timeCount = timeList.length;
      const isFill = timeCount > 0 && !timeList.find(item => item.useStatus == 0);

      return {
        date, month, year, value, isFill, timeCount
      };
    }
  }
})